﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using System.Linq;
using System.Collections.Generic;
using TyMES.Model.Record;
using TyMES.ViewModel.Record.PersonLayOffRecordVMs;
using TyMES.Model;
using Newtonsoft.Json;
using TyMES.Model.BaseInformation;
using TyMES.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace TyMES.Record.Controllers
{
    [AuthorizeJwtWithCookie]
    [ActionDescription("_Model.PersonLayOffRecord")]
    [ApiController]
    [Route("/api/Record/PersonLayOffRecord")]
    public partial class PersonLayOffRecordController : BaseApiController
    {
        private readonly ILogger logger;
        private readonly IConfiguration configuration;
        private readonly HttpService httpService;
        private readonly IServiceScope serviceScope;
        private readonly WTMContext context;
        private string _LineCode;
        private string factoryCode;
        private string mesIP;
        private string mesPort;


        public PersonLayOffRecordController(ILogger<PassStationService> logger, IConfiguration configuration, HttpService httpService, IServiceScopeFactory serviceScopeFactory)
        {
            this.logger = logger;
            this.configuration = configuration;
            this.httpService = httpService;
            this.serviceScope = serviceScopeFactory.CreateScope();
            var sp = this.serviceScope.ServiceProvider;
            this.context = sp.GetRequiredService<WTMContext>();
            this.factoryCode = configuration["FactoryCode"];
            this.mesIP = configuration["MESIP"];
            this.mesPort = configuration["MESPORT"];
            _LineCode = configuration["LineCode"];
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public IActionResult Get(string id)
        {
            var vm = Wtm.CreateVM<PersonLayOffRecordVM>(id);
            return Ok(vm);
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("[action]")]
        public async Task<IActionResult> Create(PersonLayOffRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoAddAsync();
   
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("[action]")]
        public async Task<IActionResult> Edit(PersonLayOffRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoEditAsync(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }
                

        [HttpPost("BatchEdit")]
        [ActionDescription("Sys.BatchEdit")]
        public ActionResult BatchEdit(PersonLayOffRecordBatchVM vm)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(vm.Ids.Count());
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<PersonLayOffRecordBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<PersonLayOffRecordImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(PersonLayOffRecordImportVM vm)
        {

            if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm.EntityList.Count);
            }
        }


        [ActionDescription("上下岗信息同步")]
        [HttpPost("OnorOffduty")]
        public async Task<IActionResult> OnorOffduty(PersonInfo personInfo)
        {
            responseMes3 responseMes = new responseMes3();
            //var persondetial = DC.Set<Person>().Where(x => x.PersonCode == personInfo.empCode).ToList();
            if (PersonVerify(personInfo))
            {
                OnorOffrequest onorOffdutyinfo = new OnorOffrequest();
                onorOffdutyinfo.serviceId = "EmployeeWorkService_FaceIdentifyWorkOnOff";
                onorOffdutyinfo.factoryCode = factoryCode;
                onorOffdutyinfo.requestTime = DateTime.Now;

                onorOffdutyinfo.data = new List<PersonInfo> { personInfo };

                string postdata = JsonConvert.SerializeObject(onorOffdutyinfo);
                try
                {
                    string value = await httpService.PostDataAsync("http://" + mesIP + ":" + mesPort + "/api/base/Base_Information", postdata);
                    try
                    {
                        OnorOffdutyresponse onorOffdutyresponse = new OnorOffdutyresponse();
                        onorOffdutyresponse = JsonConvert.DeserializeObject<OnorOffdutyresponse>(value);
                        responseMes = JsonConvert.DeserializeObject <responseMes3 >(onorOffdutyresponse.data.data);
                        if (responseMes.code == "000000")
                        {
                            PersonLayOffRecord personNote = new PersonLayOffRecord();
                            personNote.PersonCode = personInfo.empCode;
                            //personNote.PersonName = persondetial[0].PersonName;
                            personNote.Opertion = responseMes.code + ":" + responseMes.mesg;
                            personNote.OperatonTime = personInfo.identificationDate;
                            DC.Set<PersonLayOffRecord>().Add(personNote);
                            DC.SaveChanges();
                            return Ok(responseMes);
                        }
                        else
                        {
                            PersonLayOffRecord personNote = new PersonLayOffRecord();
                            personNote.PersonCode = personInfo.empCode;
                            //personNote.PersonName = persondetial[0].PersonName;
                            personNote.Opertion = responseMes.code + ":" + responseMes.mesg;
                            personNote.OperatonTime = personInfo.identificationDate;
                            DC.Set<PersonLayOffRecord>().Add(personNote);
                            DC.SaveChanges();
                            return Ok(responseMes);
                        }
                    }
                    catch (Exception ex)
                    {
                        PersonLayOffRecord personNote = new PersonLayOffRecord();
                        personNote.PersonCode = personInfo.empCode;
                        //personNote.PersonName = persondetial[0].PersonName;
                        personNote.Opertion = ex.Message;
                        DC.Set<PersonLayOffRecord>().Add(personNote);
                        DC.SaveChanges();
                        responseMes.mesg = ex.Message;
                        return Ok(responseMes);
                    }
                }
                catch (Exception ex)
                {
                    return Ok(ex.Message);
                }


            }
            else
            {
                PersonLayOffRecord personNote = new PersonLayOffRecord();
                personNote.PersonCode = personInfo.empCode;
                //personNote.PersonName = persondetial[0].PersonName;
                personNote.Opertion = "人员资质校验失败";
                DC.Set<PersonLayOffRecord>().Add(personNote);
                DC.SaveChanges();
                responseMes.mesg = "人员资质校验失败";
                return Ok(responseMes);
            }


        }

        

        public class OnorOffdutyresponse
        {
            public string code { get; set; }
            public bool success { get; set; }
            public bool fail { get; set; }
            public string mesg { get; set; }
            public responseMes data { get; set; }
            public string time { get; set; }
        }
        public class responseMes
        {
            public string code { get; set; }
            public bool success { get; set; }
            public bool fail { get; set; }
            public string mesg { get; set; }
            public string data { get; set; }
            public string time { get; set; }
        }
        public class responseMes3
        {
            public string code { get; set; }
            
            public string mesg { get; set; }
            
            public string time { get; set; }
        }
        public class responseMes2
        {
            public string code { get; set; }
            public string mesg { get; set; }
            public string time { get; set; }
        }

        //人员资质校验
        public bool PersonVerify(PersonInfo personInfo)
        {
            return true;
        }
        public class OnorOffrequest
        {
            public string serviceId { get; set; }
            public string factoryCode { get; set; }
            public DateTime requestTime { get; set; }
            public List<PersonInfo> data { get; set; }
        }

        public class PersonInfo
        {
            public string empCode { get; set; }
            public string identificationDate { get; set; }
            public string stationCode { get; set; }

        }



    }
}